package com.atguigu.controller;

import com.atguigu.entity.HouseImage;
import com.atguigu.result.Result;
import com.atguigu.service.HouseImageService;
import com.atguigu.util.QiniuUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

/**
 * @Author:hx
 * @DateTime:2022/9/29 13:49
 * @Description:
 */
@Controller
@RequestMapping("/houseImage")
public class HouseImageController {
    @DubboReference
    private HouseImageService houseImageService;

    @RequestMapping("/uploadShow/{houseId}/{type}")
    public String uploadShow(Model model, @PathVariable("houseId") Long houseId,@PathVariable("type") Long type){
        model.addAttribute("houseId",houseId);
        model.addAttribute("type",type);
        return "house/upload";
    }

    /**
     * @Description 上传图片
     * @param houseId:
     * @param type:
     * @param files:
     * @return: com.atguigu.result.Result
     */
    @RequestMapping("/upload/{houseId}/{type}")
    @ResponseBody
    public Result upload(@PathVariable("houseId") Long houseId, @PathVariable("type") Integer type, @RequestParam("file") MultipartFile[] files) throws IOException {
        //获取图片
        for (MultipartFile file : files) {
            String originalFilename = file.getOriginalFilename();
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            String fileName = UUID.randomUUID().toString() + suffix;
            HouseImage houseImage = new HouseImage();
            houseImage.setHouseId(houseId);
            houseImage.setType(type);
            houseImage.setImageName(fileName);
            houseImage.setImageUrl("http://riyliglse.hn-bkt.clouddn.com/"+fileName);
            //上传到数据库
            houseImageService.insert(houseImage);
            //上传到服务器
            QiniuUtils.upload2Qiniu(file.getBytes(),fileName);

        }
        return Result.ok();
    }

    @RequestMapping("/delete/{houseId}/{id}")
    public String delete(@PathVariable("houseId") Long houseId,@PathVariable("id") Long id){
        HouseImage houseImage = houseImageService.getById(id);
        QiniuUtils.deleteFileFromQiniu(houseImage.getImageName());
        houseImageService.delete(id);
        return "redirect:/house/"+houseId;
    }
}
